import store from '@/store'
import Layout from '@/layout'
import router from '@/router'
import { constantRoutes } from '@/router'
import { postRequest } from '@/utils/request'
import { isEmpty,isNotEmpty } from '@/utils/validate'
import { getUser } from '@/utils/cookies'



function handleWrapperRoute(route) {
    return  {
        path: isNotEmpty(route.vueUrl) ? route.vueUrl : route.reqUrl,
        name: route.name,
        //todo 必须加上.vue,其实应该不用加，待研究
        // component: isNotEmpty(route.vueComponent)  ? () => import('@/views/'+route.vueComponent+'.vue') : Layout,
        component: isNotEmpty(route.vueComponent)  ? (resolve) => require(['@/views' + route.vueComponent], resolve) : Layout,
        hidden: route.pid === -1,
        meta: {
            id: route.id,
            pid: route.pid,
            title: route.name,
            icon: route.icon,
            type: route.type
        }
    }
}

function handleFetchAsyncRoutes(routes) {
    let ar = []
    routes.forEach(r =>{
        if (r.pid === 0 && r.status === 1) {
            let route = handleWrapperRoute(r);
            handleRecursionAsyncRoutes(route,routes);
            ar.push(route)
        }
    })
    // 404 page must be placed at the end !!!
    ar.push({ path: '*', redirect: '/404', hidden: true })
    return ar
}

/**
 * Filter asynchronous routing tables by recursion(递归)
 */
function handleRecursionAsyncRoutes(parentRoute,routes) {

    for (let i = 0; i < routes.length; i++) {
        let route = routes[i];
        let pid = parentRoute.meta.id
        if (route.pid > 0 && route.type !== 2 && route.status === 1) {
            if (pid === route.pid) {
                if (isEmpty(parentRoute.children)) {
                    parentRoute.children = [];
                }
                let _route = handleWrapperRoute(route);
                parentRoute.children.push(_route);
                handleRecursionAsyncRoutes(_route,routes);
            }
        }
    }
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    }
}

const actions = {
    generateRoutes({commit}) {
        let roles =  getUser().roles || store.getters.userInfo.roles
        return new Promise((resolve, reject) => {
            postRequest('/permission/menuList', roles.map(m=>m.id)).then(res => {
                let accessedRoutes = handleFetchAsyncRoutes(res.content)
                commit('SET_ROUTES',accessedRoutes)
                store.commit('SET_ROLE',roles)
                router.addRoutes(accessedRoutes)
                resolve(accessedRoutes)
            }).catch(error => {
                console.log(error)
                reject(error)
            })
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
